import axios from 'axios'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { blobValidate } from '@/utils/ruoyi'
import { S3, GetObjectCommand } from "@aws-sdk/client-s3";
import * as binconv from 'binconv';
const baseURL = import.meta.env.VITE_APP_BASE_API;
let s3;
function init() {
  s3 = new S3({
    endpoint: "https://obs-sdjn.cucloud.cn",
    region: "cn-jinan-1",
    credentials: {
      accessKeyId: "5ACB4AFF127645D78BFBD861991425C04899",
      secretAccessKey: "5D38D10BF8E24A1BBA6F95B0DB72DB6C2234",
    },
    forcePathStyle: true,
    signatureVersion: 'v4'
  });
}
export default {
  zip(url, name) {
    var url = baseURL + url
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then(async (res) => {
      const isLogin = await blobValidate(res.data);
      if (isLogin) {
        const blob = new Blob([res.data])
        this.saveAs(blob, name)
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  file(id, name) {
    return new Promise((resolve, reject) => {
      var url = baseURL + "/system/file/share/download/" + id;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          this.saveAs(blob, name)
          resolve('success')
        } else {
          this.printErrMsg(res.data)
          reject('error')
        }
      })
    })
  },
  localFile(id, name) {
    return new Promise((resolve, reject) => {
      var url = baseURL + "/system/file/download/" + id;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          this.saveAs(blob, name)
          resolve('success')
        } else {
          this.printErrMsg(res.data)
          reject('error')
        }
      })
    })
  },
  authFile(id, name) {
    return new Promise((resolve, reject) => {
      var url = baseURL + "/system/file/download/auth/" + id;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          this.saveAs(blob, name)
          resolve('success')
        } else {
          this.printErrMsg(res.data)
          reject('error')
        }
      }).catch(resp => {
        reject()
      })
    })
  },
  ossFile(Bucket, name) {
    let params = {
      Bucket: Bucket,
      Key: name,
    };
    return new Promise(async (resolve, reject) => {
      const that = this;
      if (!s3) {
        init();
      }
      const command = new GetObjectCommand(params);
      const response = await s3.send(command);
      const body = await binconv.readableStreamToBlob(response.Body);
      const blob = new Blob([body])
      that.saveAs(blob, params.Key);
      resolve('success')
    });
  },
  ossFileByte(Bucket, name) {
      let params = {
        Bucket: Bucket,
        Key: name,
      };
      return new Promise(async (resolve, reject) => {
        const that = this;
        if (!s3) {
          init();
        }
        const command = new GetObjectCommand(params);
        const response = await s3.send(command);
        const body = await binconv.readableStreamToBlob(response.Body);
        const blob = new Blob([body])
        resolve(blob)
      });
  },
  saveAs(text, name, opts) {
    saveAs(text, name, opts);
  },
  //根据文件名字显示图片
  previewPicByName(name) {
    return new Promise((resolve, reject) => {
      var url = baseURL + "/system/file/download?fileName=" + name;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          resolve(URL.createObjectURL(blob));
        } else {
          reject('未找到图片');
        }
      })
    });
  },
  //根据id显示图片
  previewPicById(id) {
    return new Promise((resolve, reject) => {
      var url = baseURL + "/system/file/download/" + id;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          resolve(URL.createObjectURL(blob));
        } else {
          reject('未找到图片');
        }
      })
    });
  },
  //根据id显示图片
  previewSharePicById(id) {
    return new Promise((resolve, reject) => {
      var url = baseURL + "/system/file/share/download/" + id;
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then(async (res) => {
        const isLogin = await blobValidate(res.data);
        if (isLogin) {
          const blob = new Blob([res.data])
          resolve(URL.createObjectURL(blob));
        } else {
          reject('未找到图片');
        }
      })
    });
  },
  async printErrMsg(data) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg);
  }
}

